package com.nhjf.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.nhjf.common.util.Properties.SysProperties;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


@SuppressWarnings("restriction")
public class ImageUtil {
	
	public static void main(String args[]){
		try{
			ImageUtil.doCompress("C:/1.jpg", "C:/2.jpg");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 读取图片文件
	 * @param imagePath 图片地址
	 * @return
	 */
	private static BufferedImage readImage(String imagePath) throws Exception{
		// 构造BufferedImage对象  
		BufferedImage srcImage = null;  
		FileInputStream in = null;
        File file = new File(imagePath);  
        in = new FileInputStream(file);  
        byte[] b = new byte[5];  
        in.read(b);  
        srcImage = javax.imageio.ImageIO.read(file); 
        in.close();
        return srcImage;  
	}
	
	
	/**
	 * 将图片文件输出到指定的路径，并设定压缩质量 
	 * @param srcImagePath 原图地址
	 * @param targetImagePath 压缩图片地址
	 * @param quality 压缩质量
	 * @throws Exception
	 */
	public static void doCompress(String srcImagePath,String targetImagePath) throws Exception{
    	 // 判断输出的文件夹路径是否存在，不存在则创建  
        File file = new File(targetImagePath);  
        if (!file.getParentFile().exists()) {  
            file.getParentFile().mkdirs();  
        }
        
        float quality = Float.valueOf(SysProperties.getInstance().get("quality"));
        FileOutputStream targetImage = new FileOutputStream(targetImagePath); 
        BufferedImage srcImage = readImage(srcImagePath);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(targetImage);  
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(srcImage);  
        // 压缩质量  
        jep.setQuality(quality, true);  
        encoder.encode(srcImage, jep);  
        targetImage.close();  
    }
}
